﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.WebPartPages;
using zevenseas.LifeCycleManagement.Utilities;

namespace zevenseas.LifeCycleManagement.EventReceivers
{
    public class CreateLCMWebFeatureReceiver : SPFeatureReceiver 
    {
        private ErrorHandling errorHandling;

        public CreateLCMWebFeatureReceiver()
        {           
            errorHandling = new ErrorHandling();
            errorHandling.productName = "CreateLCMWebFeatureReceiver";
            errorHandling.exeName = "zevenseas.LifeCycleManagement.EventReceivers";
        }

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPAdministrationWebApplication webApplication = SPAdministrationWebApplication.Local;
            SPWeb currentWeb = webApplication.Sites[0].RootWeb;
            
            CreateWeb(currentWeb);
            CreateList(currentWeb);
            AddWebParts(currentWeb);
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPAdministrationWebApplication webApplication = SPAdministrationWebApplication.Local;
            SPWeb currentWeb = webApplication.Sites[0].RootWeb;
            
            DeleteWeb(currentWeb);
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
        }

        private void DeleteWeb(SPWeb web)
        {
            try
            {
                web.Site.AllWebs["LCM"].Delete();                
            }
            catch (Exception siteCreationError)
            {
                errorHandling.LogMessage(siteCreationError.Message.ToString(), siteCreationError);
            }
        }

        private void CreateWeb(SPWeb web)
        {
            try
            {
                SPWebApplication centralAdminWebApplication = SPAdministrationWebApplication.Local;
                SPWeb centralAdminWeb = centralAdminWebApplication.Sites[0].RootWeb;

                SPGroup adminUsers = centralAdminWeb.SiteGroups["Farm Administrators"];
                string centralAdminApplicationPoolAccount = centralAdminWebApplication.ApplicationPool.Username;

                List<string> applicationPoolAccounts = new List<string>();

                SPWebApplicationCollection webApplicationCollection = SPWebService.ContentService.WebApplications;
                foreach (SPWebApplication webApplication in webApplicationCollection)
                {
                    if (!applicationPoolAccounts.Contains(webApplication.ApplicationPool.Username))
                    {
                        applicationPoolAccounts.Add(webApplication.ApplicationPool.Username);
                    }
                }

                SPWeb LCMweb = centralAdminWeb.Webs.Add("LCM", "Life Cycle Management Logging and Analytical Site", "", Convert.ToUInt32(1033), "STS#0", true, false);

                LCMweb.CreateDefaultAssociatedGroups(centralAdminApplicationPoolAccount, "", "");
                foreach (string applicationPoolAccount in applicationPoolAccounts)
                {
                    LCMweb.AssociatedOwnerGroup.AddUser(applicationPoolAccount, "", "", "");
                }

                foreach (SPUser user in adminUsers.Users)
                {
                    LCMweb.AssociatedOwnerGroup.AddUser(user);
                }


                Utilities.Utilities.SetWebProperty("true", "LCMSiteCreated", web.Properties);
            }
            catch (Exception siteDeletionnError)
            {
                Utilities.Utilities.SetWebProperty("false", "LCMSiteCreated", web.Properties);
                errorHandling.LogMessage(siteDeletionnError.Message.ToString(), siteDeletionnError);
            }
        }

        private void CreateList(SPWeb web)
        {
            using (SPWeb LCMWeb = web.Webs["LCM"])
            {

                LCMWeb.Lists.Add("DeletedSites", "Overview of all the sites and webs that have been deleted", SPListTemplateType.GenericList);
                SPList deletedSitesList = LCMWeb.Lists["DeletedSites"];
                deletedSitesList.EnableAttachments = false;
                deletedSitesList.EnableVersioning = false;
                deletedSitesList.OnQuickLaunch = true;
                deletedSitesList.Fields.Add("SiteCollection", SPFieldType.Boolean, false);
                deletedSitesList.Fields.Add("Web", SPFieldType.Boolean, false);
                deletedSitesList.Fields.Add("Url", SPFieldType.Text, false);
                deletedSitesList.Fields.Add("Date", SPFieldType.DateTime, false);
                deletedSitesList.Fields.Add("Size", SPFieldType.Text, false);
                deletedSitesList.Fields.Add("FileName", SPFieldType.Text, false);
                deletedSitesList.Fields.Add("FileLocation", SPFieldType.Text, false);
                deletedSitesList.Fields.Add("WebApplication", SPFieldType.Text, false);
                deletedSitesList.Update();

                SPView deletedSitesView = deletedSitesList.DefaultView;
                deletedSitesView.ViewFields.Add("WebApplication");
                deletedSitesView.ViewFields.Add("SiteCollection");
                deletedSitesView.ViewFields.Add("Web");
                deletedSitesView.ViewFields.Add("Url");
                deletedSitesView.ViewFields.Add("Date");
                deletedSitesView.ViewFields.Add("Size");
                deletedSitesView.ViewFields.Add("FileName");
                deletedSitesView.ViewFields.Add("FileLocation");
                deletedSitesView.Update();

                LCMWeb.Lists.Add("UnusedSites", "Overview of all the sites that are not being used for a period of time", SPListTemplateType.GenericList);
                SPList unusedSitesList = LCMWeb.Lists["UnusedSites"];
                unusedSitesList.EnableAttachments = false;
                unusedSitesList.EnableVersioning = false;
                unusedSitesList.OnQuickLaunch = true;
                unusedSitesList.Fields.Add("WebApplication", SPFieldType.Text, false);
                unusedSitesList.Fields.Add("SiteCollection", SPFieldType.Text, false);
                unusedSitesList.Fields.Add("Status", SPFieldType.Choice, false);
                unusedSitesList.Fields.Add("Web", SPFieldType.Text, false);
                unusedSitesList.Fields.Add("Url", SPFieldType.Text, false);
                unusedSitesList.Fields.Add("LastUsageDate", SPFieldType.DateTime, false);
                unusedSitesList.Fields.Add("Size", SPFieldType.Text, false);
                unusedSitesList.Fields.Add("OwnerEmailAddress", SPFieldType.Text, false);
                

                SPFieldChoice statusField = (SPFieldChoice)unusedSitesList.Fields["Status"];
                statusField.Choices.Add("Mail");
                statusField.Choices.Add("Lock");
                statusField.Choices.Add("Delete");

                unusedSitesList.Fields.Add("Locked", SPFieldType.Boolean, false);
                unusedSitesList.Fields.Add("LockedAt", SPFieldType.DateTime, false);
                unusedSitesList.Fields.Add("Mailed", SPFieldType.Boolean, false);
                unusedSitesList.Fields.Add("MailedAt", SPFieldType.DateTime, false);
                unusedSitesList.Fields.Add("AmountOfMails", SPFieldType.DateTime, false);
                unusedSitesList.Fields.Add("Deleted", SPFieldType.Boolean, false);
                unusedSitesList.Fields.Add("DeletedAt", SPFieldType.DateTime, false);

                unusedSitesList.Update();

                SPView unusedListView = unusedSitesList.DefaultView;
                unusedListView.ViewFields.Add("WebApplication");
                unusedListView.ViewFields.Add("SiteCollection");
                unusedListView.ViewFields.Add("Web");
                unusedListView.ViewFields.Add("Url");
                unusedListView.ViewFields.Add("Status");
                unusedListView.ViewFields.Add("LastUsageDate");
                unusedListView.ViewFields.Add("Size");
                unusedListView.ViewFields.Add("OwnerEmailAddress");
                unusedListView.ViewFields.Add("Locked");
                unusedListView.ViewFields.Add("LockedAt");
                unusedListView.ViewFields.Add("Mailed");
                unusedListView.ViewFields.Add("MailedAt");
                unusedListView.ViewFields.Add("AmountOfMails");
                unusedListView.ViewFields.Add("Deleted");
                unusedListView.ViewFields.Add("DeletedAt");

                unusedListView.Update();
            }
        }

        private void AddWebParts(SPWeb web)
        {
            using (SPWeb LCMWeb = web.Webs["LCM"])
            {
                SPList deletedSitesList = LCMWeb.Lists["DeletedSites"];
                SPList unusedSitesList = LCMWeb.Lists["UnusedSites"];

                ListViewWebPart deletedSitesWebPart = Utilities.Utilities.CreateListViewWebPart(deletedSitesList);
                ListViewWebPart unusedSitesWebPart = Utilities.Utilities.CreateListViewWebPart(unusedSitesList);

                SPLimitedWebPartManager webpartManager = LCMWeb.GetLimitedWebPartManager("default.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
                webpartManager.AddWebPart(deletedSitesWebPart, "Left", 1);
                webpartManager.AddWebPart(unusedSitesWebPart, "Left", 2);


                Utilities.Utilities.DisableToolbar(deletedSitesWebPart);
                Utilities.Utilities.DisableToolbar(unusedSitesWebPart);
            }
        }
    }
}
